﻿using UnityEngine;
using Cysharp.Threading.Tasks;

public class PlayerSpawner : USaBehaviour
{
    [SerializeField, Tooltip("当前重生点编号")]
    public int id;


    private const string PREFAB_ROOT_PATH = "PlayerPrefabs/{0}.prefab";
    private static AssetCache<string, GameObject> s_PlayerPrefabCaches = new AssetCache<string, GameObject>(PREFAB_ROOT_PATH);
    private static ObjectPool<PlayerEntity> s_Pool = null;


    private async void Awake()
    {
        if (s_Pool == null)
        {
            var prefab = await s_PlayerPrefabCaches.LoadAsync("player");
            s_Pool = new ObjectPool<PlayerEntity>(prefab, ent =>
            {
                ent.Init();
            });
            var player = s_Pool.Rent();
            SceneOrganizer.playerInstance = player;
            DontDestroyOnLoad(player);
            Spawn();
        }
    }

    public void Spawn()
    {
        var player = SceneOrganizer.playerInstance;
        player.gameObject.SetActive(true);
        player.transform.position = transform.position;
        player.Spawn();
    }

    public void Despawn()
    {
        var player = SceneOrganizer.playerInstance;
        player.Despawn();
        player.gameObject.SetActive(false);
    }

    public void Respawn()
    {
        var player = SceneOrganizer.playerInstance;
        player.Despawn();
        player.transform.position = transform.position;
        player.Spawn();
    }

    public void ShowPlayer()
    {
        SceneOrganizer.playerInstance.gameObject.SetActive(true);
    }

    public void HidePlayer()
    {
        SceneOrganizer.playerInstance.gameObject.SetActive(false);
    }
}